package com.pingba.controller;

import com.pingba.common.Constant;
import com.pingba.entity.User;
import com.pingba.entity.friend.BlackList;
import com.pingba.entity.msg.MsgType;
import com.pingba.executor.Station;
import com.pingba.service.UserService;
import com.pingba.service.friend.BlackListService;
import com.pingba.service.friend.FriendRelationService;
import com.pingba.service.msg.MsgTypeService;
import com.pingba.util.ReturnHelp;
import com.pingba.util.helper.JsonHelp;
import com.pingba.util.helper.StrHelper;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * Created by Administrator on 2015/10/25 0025.
 */
@Controller
@RequestMapping(value = "/pingba/user", method = {RequestMethod.GET,RequestMethod.POST})
public class UserController {
    private static Logger logger = Logger.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private MsgTypeService msgTypeService;
    @Autowired
    private FriendRelationService friendRelationService;
    @Autowired
    private BlackListService blackListService;

    @Autowired
    private Station station;







    /**
     * 通过手机号查找用户并返回
     * @param phone
     * @return
     */
    @RequestMapping("/getUserByPhone")
    @ResponseBody
    public String getUserByPhone(@RequestParam("phone") String phone) {
        User user = userService.findPhoneUser(phone);
        if (user == null) {
            return ReturnHelp.getReturnString(false, "none user find");
        }
        return ReturnHelp.getReturnString(true, JsonHelp.jsonFromObject(user));
    }

    /**
     * 通过id查找用户并返回
     * @param id
     * @return
     */
    @RequestMapping("/getUserById")
    @ResponseBody
    public String getUserById(@RequestParam("id") Long id) {
        User user = userService.findIdUser(id);
        if (user == null) {
            return ReturnHelp.getReturnString(false, "none user find");
        }
        return ReturnHelp.getReturnString(true, JsonHelp.jsonFromObject(user));
    }

    /**
     * 检查手机是否被注册
     * @param phone
     * @return
     */
    @RequestMapping("/isRegister")
    @ResponseBody
    public String isRegistered(@RequestParam("phone") String phone) {
        Map<String,Object> returnMap = new HashMap<String, Object>();
        User user = userService.findPhoneUser(phone);

        if (user == null) {
            returnMap.put("result", true);
        } else {
            returnMap.put("result",false);
        }
        return JsonHelp.jsonFromObject(returnMap);
    }

    /**
     * 用户注册
     * @param session
     * @param phone
     * @param passwd
     * @return
     */
    @RequestMapping("/register")
    @ResponseBody
    public String register(HttpSession session, @RequestParam String phone, @RequestParam String passwd) {
        User user = userService.findPhoneUser(phone);
        if (user != null) {
            return ReturnHelp.getReturnString(false,Constant.PhoneHasUsed);
        }

        user = new User();
        user.setPhone(phone);
        user.setNickName(phone);
        user.setAge(18);
        user.setPasswd(passwd);
        user.setRegTime(new Date().getTime());
        user.setMale(true);

        userService.insert(user);
        logger.info("user register: " + user);
        session.setAttribute(Constant.UserInSession, user);
        return  ReturnHelp.getReturnString(true,user);
    }

    /**
     * 修改密码
     * @param phone
     * @param passwd
     * @return
     */
    @RequestMapping("/changePasswd")
    @ResponseBody
    public String changePasswd(@RequestParam("phone") String phone, @RequestParam("passwd") String passwd) {
        userService.setPasswd(phone, passwd);
        logger.info("phone " + phone + " changed passwd to: " + passwd);
        return ReturnHelp.getReturnString(true, "success");
    }

    /**
     * 重置密码
     * @param phone
     * @param passwd
     * @return
     */
    @RequestMapping("/resetPasswd")
    @ResponseBody
    public String resetPasswd(@RequestParam("phone") String phone, @RequestParam("passwd") String passwd) {

        userService.setPasswd(phone, passwd);
        logger.info("phone " + phone + " reset passwd to: " + passwd);
        return ReturnHelp.getReturnString(true, "success");
    }

    /**
     * 用户登录
     * @param phone
     * @param passwd
     * @param session
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public String login(@RequestParam("phone") String phone, @RequestParam("passwd") String passwd, HttpSession session) {
        User user = userService.login(phone, passwd);
        if (user == null) {
            logger.info("user login: " + phone + " with wrong passwd");
            return ReturnHelp.getReturnString(false, Constant.WrongPhoneOrPasswd);
        }
        logger.info("user login: " + phone + "at:" + new Date());
        Date now = new Date();
        user.setLastLoginDay(now.getTime());
        userService.updateLoginTime(user.getPhone(), now.getTime());
        session.setAttribute(Constant.UserInSession, user);
        return ReturnHelp.getReturnString(true,user);

    }

    /**
     * 用户注销
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    @ResponseBody
    public String  logout(HttpSession session) {
        session.invalidate();
        return ReturnHelp.getReturnString(true, "logout suceess");
    }

    /**
     * 修改用户的个人信息
     * @param session
     * @param userInfo
     * @return
     */
    @RequestMapping("/changeInfo")
    @ResponseBody
    public String changeInfo(HttpSession session, @RequestParam("userInfo") String userInfo) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false,Constant.NeedLoginMsg);
        }
        logger.info("change info: " +  userInfo);
        User userUpdate = JsonHelp.objectFromJson(userInfo, User.class);
        userUpdate.setPhone(user.getPhone());
        userService.updateInfo(userUpdate);
        return ReturnHelp.getReturnString(true, Constant.SuccessMsg);
    }

    /**
     * 修改用户的头像
     * @param session
     * @param headUrl
     * @return
     */
    @RequestMapping("/changeHeadUrl")
    @ResponseBody
    public String changeHeadUrl(HttpSession session, @RequestParam("headUrl") String headUrl) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }
        user.setHeadUrl(headUrl);
        user.setHeadChangeTime(new Date().getTime());
        userService.updateHeadUrlChangeTime(user);
        return ReturnHelp.getReturnString(true, Constant.SuccessMsg);
    }


    /**
     * 心跳机制,供客户端查询所有的新消息
     * @param session
     * @return
     */
    @RequestMapping(value = "heartBeat", method = RequestMethod.POST)
    @ResponseBody
    public String heartBeat(HttpSession session) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }

        return ReturnHelp.getReturnString(true, station.getUserMsgInfo(user));
    }

    /**
     * 查找我的朋友
     * @param session
     * @return
     */
    @RequestMapping(value = "myFriends",method = RequestMethod.POST)
    @ResponseBody
    public String myFriends(HttpSession session) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }
        return ReturnHelp.getReturnString(true, friendRelationService.getMyFriends(user.getSid()));
    }


    /**
     * 获取所有的消息类型
     * @return
     */
    @RequestMapping("msgType")
    @ResponseBody
    public String getMsgType() {
        List<MsgType> msgTypeList = msgTypeService.selectList();
        logger.info("msgTypeList is: " + msgTypeList);
        JsonHelp.jsonFromObject(msgTypeList);
        return ReturnHelp.getReturnString(true,msgTypeList);
    }


    /**
     * 增加黑名单用户
     * @param session
     * @param ignoreUserId
     * @return
     */
    @RequestMapping("blackUser/add")
    @ResponseBody
    public String blackListAdd(HttpSession session, @RequestParam("ignoreUserId") Long ignoreUserId) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }
        logger.info("user: " + user.getSid() + " ignore user: " + ignoreUserId);
        BlackList blacklist = BlackList.getDefault(user.getSid(), ignoreUserId);
        blackListService.igoreUser(blacklist);
        return ReturnHelp.getReturnString(true, Constant.SuccessMsg);
    }

    /**
     * 获取所有被我屏蔽的用户
     * @param session
     * @return
     */
    @RequestMapping("blackUser/myIgnores")
    @ResponseBody
    public String blackListMyIgnores(HttpSession session) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }
        List<User> myIgnores = blackListService.myBlackLists(user);
        return ReturnHelp.getReturnString(true, JsonHelp.jsonFromObject(myIgnores));
    }

    /**
     * 判断一个用户是否是被屏蔽
     * @param session
     * @param ignoreUserId long
     * @return
     */
    @RequestMapping("blackUser/isIgnore")
    @ResponseBody
    public String blackListIsIgnore(HttpSession session, @RequestParam("ignoreUserId") Long ignoreUserId) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }
        BlackList blackList = new BlackList();
        blackList.setUserId(user.getSid());
        blackList.setIgnoreId(ignoreUserId);
        boolean isIgnored = blackListService.isIgnored(blackList);
        return ReturnHelp.getReturnString(true, isIgnored);
    }


    /**
     * 取消某一个用户的黑名单状态
     * @param session
     * @param ignoreUserId
     * @return
     */
    @RequestMapping("blackUser/recover")
    @ResponseBody
    public String blackListRocover(HttpSession session, @RequestParam("ignoreUserId") Long ignoreUserId) {
        User user = (User) session.getAttribute(Constant.UserInSession);
        if (user == null) {
            return ReturnHelp.getReturnString(false, Constant.NeedLoginMsg);
        }
        BlackList blackList = new BlackList();
        blackList.setUserId(user.getSid());
        blackList.setIgnoreId(ignoreUserId);
        blackListService.recoverUser(blackList);
        logger.info("user: " + user.getSid() + "recover a blackUser: " + ignoreUserId);
        return ReturnHelp.getReturnString(true, Constant.SuccessMsg);
    }


    /**
     * 通过userId的list获取List<User></>
     * @param session
     * @param userIdList
     * @return
     */
    @RequestMapping("getUserList")
    @ResponseBody
    public String getUsers(HttpSession session, @RequestParam("userIdList") String userIdList) {
        logger.info("userIdList is: " + userIdList);
        List<User> userList = new ArrayList<User>();

        ArrayList<Double> objList = JsonHelp.objectFromJson(userIdList, (new ArrayList<String>()).getClass());
        for (Double l: objList) {
            User u = userService.findIdUser(l.intValue());
            userList.add(u);
        }

        return ReturnHelp.getReturnString(true, userList);

    }
}
